<script>
import {
  AddContestList,
  DeleteContestList,
  GetContestList,
  GetContestListById,
  UpdateContestList,
  UploadFile,
  GetJudgesList,
  UpdateJudgesList,
  GetContestListByName
} from "@/api/back/contest";
import { ElMessage, messageConfig, ElMessageBox } from "element-plus";
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

export default {
  components: { Editor, Toolbar },
  data() {
    return {
      // 学院信息
      collegeOptions: [
        {
          id: "1",
          college: "智能制造学院"
        },
        {
          id: "2",
          college: "人文学院"
        },
        {
          id: "3",
          college: "设计学院"
        },
        {
          id: "4",
          college: "烹饪学院"
        },
        {
          id: "5",
          college: "酒店旅游与管理学院"
        },
      ],

      // 获取当前登录用户信息
      publisherOption: JSON.parse(localStorage.getItem('userInfo')).userData[0],

      // 搜索切换
      toggleSearch: false,
      // 存放获取到得数据
      contestlist: [],

      judgeslist: {
        contestId: "",
        judges: []
      },

      fileName: {
        val: ''
      },

      // 存放搜索输入框的值
      searchVal: "",

      // 控制弹窗
      edit: false,
      add: false,

      // 分页
      pageSetting: {
        page_num: 1,
        page_size: 10,
        total: 0
      },

      // 弹窗数据
      editFormData: {
        contestId: "",
        name: "",
        nickName: "",
        publisher: JSON.parse(localStorage.getItem('userInfo')).userId,
        status: 0,
        contestDetail: "",
        regStart: "",
        regEnd: "",
        contestProfileSmallPath: "",
        contestProfilePath: "",
        contestType: "",
        academy: "",
        allocated: 0,
      },


      judgesFromData: {
        selectedJudges: []
      },

      // 弹窗添加或规则
      editFormRules: {
        contestName: [{ required: true, message: "请输入赛事名称", trigger: "blur" }],
        publisher: [{ required: true, message: "请输入发布者", trigger: "blur" }],
        organizer: [{ required: true, message: "请输入主办方", trigger: "blur" }],
      },

      // 控制弹窗显示
      dialogVisible: false,
      judgesDialog: false,

      // 赛事状态在弹窗中多选择框显示对应的文字
      statusOptions: [
        { id: 0, name: "未开始" },
        { id: 1, name: "进行中" },
        { id: 2, name: "已结束" }
      ],

      typeOptions: [
        { id: 0, name: "工科" },
        { id: 1, name: "理科" },
        { id: 2, name: "文科" },
        { id: 3, name: "商科" },
        { id: 4, name: "综合" },
      ],

      // 获取到的评委数据存放在judgeslist中
      judgesOptions: [],

      editor: null,
      html: '<p>hello</p>',
      toolbarConfig: {},
      editorConfig: { placeholder: '请输入内容...' },
      mode: 'default', // or 'simple'
    };
  },
  methods: {
    // 获取数据列表，获取到的数据存放在contestlist中
    async loadContestList() {
      try {

        const response = await GetContestList(this.pageSetting);
        if (response.data) {
          this.contestlist = [];
          this.contestlist.push(...response.data.pageList);
          this.pageSetting.page_num = response.data.pageNum;
          this.pageSetting.page_size = response.data.pageSize;
          this.pageSetting.total = response.data.total;
          console.log(this.contestlist);
        } else {
          console.error("未能获取比赛列表数据。");
        }
      } catch (error) {
        console.error("获取比赛列表时出现错误：", error);
      }
    },

    // 分页功能
    handleSizeChange(size) {
      console.log(size, 'size');
      this.pageSetting.page_size = size;
      this.contestlist = []
      this.loadContestList();
    },

    handleCurrentChange(page) {
      console.log(page, 'currentPage');
      this.pageSetting.page_num = page;
      this.contestlist = []
      this.loadContestList();
    },

    // 控制添加弹窗
    createContest() {
      console.log("publisherOption", this.publisherOption)
      this.dialogVisible = true;
      this.add = true;
      this.editFormData.editFormTitle = "创建赛事"
    },
    // 编辑弹窗
    editDialog(rowData) {
      this.editFormData.editFormTitle = "编辑赛事"
      this.editFormData.contestId = rowData.contestId;
      this.editFormData.name = rowData.name;
      this.editFormData.publisher = this.publisherOption.userId;
      this.editFormData.status = rowData.status;
      this.html = rowData.contestDetail;
      this.editFormData.regStart = rowData.regStart;
      this.editFormData.regEnd = rowData.regEnd;
      this.editFormData.contestType = rowData.contestType;
      this.editFormData.contestProfilePath = rowData.contestProfilePath;
      this.editFormData.contestProfileSmallPath = rowData.contestProfileSmallPath;
      this.editFormData.academy = rowData.academy;
      this.allocated = rowData.allocated;
      this.dialogVisible = true;
      this.edit = true;

    },

    // 处理弹窗确认按钮
    async handleConfirm() {
      try {
        if (this.edit) {
          this.editFormData.contestDetail = this.html
          await UpdateContestList(this.editFormData)
          this.edit = false;
        } else if (this.add) {
          this.editFormData.contestDetail = this.html
          const res = await AddContestList(this.editFormData);
          console.log(res)
          this.loadContestList();
          this.add = false;
        }
      } catch (error) {
        console.error()
      }
      this.contestlist = [];
      this.dialogVisible = false;
      this.judgesFromData.selectedJudges = [];
      await this.loadContestList();
    },

    async handleJudgesConfirm() {
      this.judgeslist.judges = this.judgesFromData.selectedJudges
      console.log(this.judgeslist)
      try {
        await UpdateJudgesList(this.judgeslist)
      } catch (error) {
        console.error()
      }
      this.judgesDialog = false;
      this.judgeslist = [];
      await this.loadContestList();
      ElMessage({
      message: '分配成功',
      type: 'success',
      })
    },


    async distribute(row) {
      this.judgeslist.contestId = row.contestId
      this.judgesDialog = true;
    },

    // 搜索功能，根据输入赛事编号id进行搜索
    async searchById() {
      try {
        if (this.searchVal == null || this.searchVal == "") {
          GetContestList(this.pageSetting)
        } else {
          const v = {
            search: this.searchVal, // 以键值对的形式提供参数
            page: this.pageSetting
          };
          // 初始化表单
          this.contestlist = [];
          const response = await GetContestListById(v);
          this.contestlist.push(...response.data);
          // 在这里处理成功的响应数据
          console.log("成功：", response);
        }
      } catch (error) {
        console.error("搜索比赛时出现错误：", error);
      }
    },
    async searchByName() {
      if (this.searchVal == null || this.searchVal == "") {
        ElMessage({
          message: "请输入搜索内容",
          type: "warning"
        });
        return;
      }
      this.contestlist = [];
      const res = await GetContestListByName({ search: this.searchVal })
      if (res.data.length == 0) {
        ElMessage({
          message: "未找到相关赛事",
          type: "error",
        });
      } else {
        this.contestlist.push(...res.data);
      }
    },

    // 删除功能，根据赛事编号id进行删除，并重新获取数据
    async del(row) {
      const id = row.contestId; // 假设ID字段在scope.row中叫做'id'

      ElMessageBox.confirm(
        `将删除赛事${row.name}，是否继续？`,
        'Warning',
        {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          try {
            await DeleteContestList(id); // 向后端传递ID进行删除操作
            // 初始化表单
            this.contestlist = [];
            await this.loadContestList();
            ElMessage({
              message: "删除成功",
              type: "success",
              ...messageConfig,
            });
            console.log("删除成功");
          } catch (error) {
            console.error("删除比赛时出现错误：", error);
          }
        })
        .catch(() => {
          ElMessage({
            type: 'info',
            message: '取消',
          })
        })
    },

    openFileInput() {
      this.$refs.fileInput.click();
    },

    openSmallFileInput() {
      this.$refs.smallFileInput.click();
    },

    async handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        try {
          await this.uploadFile(file);
        } catch (error) {
          console.error(error);
        }
      }
    },

    async handleSmallFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        try {
          await this.uploadSmallFile(file);
        } catch (error) {
          console.error(error);
        }
      }
    },

    async uploadFile(file) {
      const formData = new FormData();
      formData.append('file', file);
      try {
        const response = await UploadFile(formData);
        const filePath = response.data;
        this.editFormData.contestProfilePath = filePath;
        // 处理响应（例如，显示成功消息或更新表单数据）
        console.log('文件上传成功', response);
      } catch (error) {
        console.error('上传文件时出错', error);
      }
    },

    async uploadSmallFile(file) {
      const formData = new FormData();
      formData.append('file', file);
      try {
        const response = await UploadFile(formData);
        const filePath = response.data;
        this.editFormData.contestProfileSmallPath = filePath;
        // 处理响应（例如，显示成功消息或更新表单数据）
        console.log('文件上传成功', response);
      } catch (error) {
        console.error('上传文件时出错', error);
      }
    },

    // 处理弹窗取消按钮
    handleBeforeClose() {
      this.editFormData.contestId = "";
      this.editFormData.name = "";
      this.editFormData.status = 0;
      this.editFormData.contestDetail = "";
      this.editFormData.publisher = JSON.parse(localStorage.getItem('userInfo')).userId;
      this.html = "";
      this.editFormData.contestType = "";
      this.editFormData.regStart = "";
      this.editFormData.regEnd = "";
      this.editFormData.contestProfilePath = "";
      this.editFormData.contestProfileSmallPath = "";
      this.editFormData.contestType = "";
      this.editFormData.academy = "";
      this.judgesFromData.selectedJudges = "";
      this.dialogVisible = false;
      this.judgesDialog = false;
      this.edit = false;
      this.add = false;
      this.editor = null;
      this.allocated = "";
    },

    async loadJudgesList() {
      try {
        this.pageSetting.roleId = 2;
        let res = await GetJudgesList(this.pageSetting)
        this.judgesOptions = res.data.pageList;
        console.log(this.judgesOptions)
      } catch (err) {
        console.log(err)
      }
    },

    onCreated(editor) {
      this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
    },
  },
  beforeUnmount() {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  },
  computed: {
    // 根据数据返回相对应的文字
    getStatusLabel() {
      return status => {
        if (status === 0) return "未开始";
        if (status === 1) return "进行中";
        if (status === 2) return "已结束";
      };
    },
    getContestTypesLabel() {
      return status => {
        if (status === 0) return "工科";
        if (status === 1) return "理科";
        if (status === 2) return "文体";
        if (status === 3) return "商科";
        if (status === 4) return "综合";
      };
    },
  },
  mounted() {
    // 调用获取赛事列表数据方法
    this.loadContestList();
    this.loadJudgesList();
  },
  // 应该搞个图片上传配置
  // setup() {
  //   const editorConfig = { MENU_CONF: {} }
  //   editorConfig.MENU_CONF['uploadImage'] = {
  //     server: '/api/upload-img',
  //     // server: '/api/upload-img-10s', // test timeout
  //     // server: '/api/upload-img-failed', // test failed
  //     // server: '/api/xxx', // test 404

  //     timeout: 5 * 1000, // 5s

  //     fieldName: 'custom-fileName',
  //     meta: { token: 'xxx', a: 100 },
  //     metaWithUrl: true, // join params to url
  //     headers: { Accept: 'text/x-json' },

  //     maxFileSize: 10 * 1024 * 1024, // 10M

  //     base64LimitSize: 5 * 1024, // insert base64 format, if file's size less than 5kb

  //     onBeforeUpload(file) {
  //       console.log('onBeforeUpload', file)

  //       return file // will upload this file
  //       // return false // prevent upload
  //     },
  //     onProgress(progress) {
  //       console.log('onProgress', progress)
  //     },
  //     onSuccess(file, res) {
  //       console.log('onSuccess', file, res)
  //     },
  //     onFailed(file, res) {
  //       alert(res.message)
  //       console.log('onFailed', file, res)
  //     },
  //     onError(file, err, res) {
  //       alert(err.message)
  //       console.error('onError', file, err, res)
  //     },

  //     // customInsert(res, insertFn) {
  //     //   console.log('customInsert', res)
  //     //   const imgInfo = res.data[0] || {}
  //     //   const { url, alt, href } = imgInfo
  //     //   if (!url) throw new Error(`Image url is empty`)

  //     //   console.log('Your image url ', url)
  //     //   insertFn(url, alt, href)
  //     // },

  //   }

  //   return {
  //     // editorConfig
  //   }
  // }
};
</script>

<template>
  <div class="container">
    <!-- 搜索跟创建赛事 -->
    <div class="content-top">
      <el-input class="search-input" v-model="searchVal" :placeholder="toggleSearch ? '请输入ID' : '请输入赛事名称'"></el-input>
      <!-- <el-tooltip :content="toggleSearch ? '切换为名称' : '切换为ID'" placement="bottom">
        <el-switch
          v-model="toggleSearch"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: rgb(19, 122, 206)"
        />
      </el-tooltip> -->
      <el-button v-if="toggleSearch" icon="Search" @click="searchById" round>搜索</el-button>
      <el-button v-else icon="Search" @click="searchByName" round>搜索</el-button>
      <el-button @click="loadContestList" round>清除搜索</el-button>
      <!-- 创建赛事按钮，round，圆角按钮 -->
      <el-button @click="createContest" type="primary" round>创建赛事</el-button>
      <div
        style="font-family: 微软雅黑;line-height:25px;margin-left: 500px;height:30px;font-size: 24px;border: 2px solid rgb(64, 158, 255);border-radius:5px;padding: 0px 20px; color: white;background-color: rgb(64, 158, 255);">
        赛事管理</div>
    </div>

    <!-- 内容表格,border:表格边框 -->
    <!-- height="calc(100vh - 264px)" -->
    <el-table :data="contestlist" border max-height="calc(100vh - 190px)">
      <el-table-column label="序号" type="index" align="center" width="85px" />
      <el-table-column label="赛事封面" prop="cover" align="center">
        <template v-slot="scope">
          <el-image style="width: 100px; height: 80px;" fit="cover" :src="scope.row.contestProfilePath" />
        </template>
      </el-table-column>
      <el-table-column label="赛事名称" prop="name" align="center" />
      <el-table-column label="发布者" prop="nickName" align="center" />
      <el-table-column label="赛事状态" prop="status" align="center">
        <template v-slot="scope">
          {{ getStatusLabel(scope.row.status) }}
        </template>
      </el-table-column>
      <el-table-column label="赛事类型" prop="contestType" align="center">
        <template v-slot="scope">
          {{ getContestTypesLabel(scope.row.contestType) }}
        </template>
      </el-table-column>
      <el-table-column label="学院" prop="academy" align="center" />
      <el-table-column label="报名开始时间" prop="regStart" align="center" />
      <el-table-column label="报名截止时间" prop="regEnd" align="center" />
      <el-table-column label="操作" align="center" width="270">
        <template v-slot="scope">
          <el-button @click="editDialog(scope.row)" type="text" icon="el-icon-edit"><el-icon>
              <Edit />
            </el-icon>编辑</el-button>
          <el-button @click="del(scope.row)" type="text" icon="el-icon-delete" style="color: red"><el-icon>
              <Delete />
            </el-icon>删除</el-button>
          <template v-if="scope.row.allocated == 0">
            <el-button @click="distribute(scope.row)" type="text" icon="el-icon-check"><el-icon>
                <Edit />
              </el-icon>分配评委</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding-left: calc(100% - 650px); text-align: right;margin-top: 10px">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="pageSetting.page_num" :page-sizes="[5, 10, 15, 20]" :page-size="pageSetting.page_size"
        layout="total, sizes, prev, pager, next, jumper" :total="pageSetting.total">
      </el-pagination>
    </div>

    <div>
      <el-dialog v-model="dialogVisible" :title="editFormData.editFormTitle" :visible="dialogVisible" width="70%"
        :before-close="handleBeforeClose">
        <el-form :model="editFormData" :rules="editFormRules" label-position="left" ref="editFormRef">
          <el-form-item label="赛事名称" prop="name">
            <el-input v-model="editFormData.name" />
          </el-form-item>
          <el-form-item label="赛事类型" prop="contestType">
            <el-select v-model="editFormData.contestType">
              <el-option v-for="(option, index) in typeOptions" :key="index" :label="option.name"
                :value="option.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="赛事状态" prop="status">
            <el-select v-model="editFormData.status">
              <el-option v-for="(option, index) in statusOptions" :key="index" :label="option.name"
                :value="option.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="报名开始时间" prop="regStart">
            <el-date-picker v-model="editFormData.regStart" type="date" placeholder="选择一个日期" />
          </el-form-item>
          <el-form-item label="报名截止时间" prop="regEnd">
            <el-date-picker v-model="editFormData.regEnd" type="date" placeholder="选择一个日期" />
          </el-form-item>
          <el-form-item label="二级学院" prop="academy">
            <!-- <el-input v-model="editFormData.academy" /> -->
            <el-select v-model="editFormData.academy" placeholder="选择二级学院">
              <el-option v-for="item in collegeOptions" :key="item.id" :label="item.college" :value="item.college" />
            </el-select>
          </el-form-item>
          <el-form-item label="赛事封面" prop="contestProfilePath">
            <el-button @click="openFileInput">上传封面</el-button>
            <input ref="fileInput" type="file" style="display: none" @change="handleFileChange">
          </el-form-item>
          <img v-show="editFormData.contestProfilePath != ''" ref="imagePreview1" :src="editFormData.contestProfilePath"
            style="height: 150px;width: 300px">
          <!-- <el-form-item label="赛事缩略图" prop="contestProfileSmallPath">
            <el-button @click="openSmallFileInput">上传缩略图</el-button>
            <input ref="smallFileInput" type="file" style="display: none" @change="handleSmallFileChange">
          </el-form-item> -->
          <!-- <img v-show="editFormData.contestProfileSmallPath != ''" ref="imagePreview2"
            :src="editFormData.contestProfileSmallPath" style="height: 150px;width: 300px"> -->
          <el-form-item label="赛事简介" prop="contestDetail">
            <div style="border: 1px solid #ccc;">
              <Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :defaultConfig="toolbarConfig"
                :mode="mode" />
              <Editor style="height: 500px; overflow-y: hidden;" v-model="html" :defaultConfig="editorConfig" :mode="mode"
                @onCreated="onCreated" />
            </div>
          </el-form-item>
        </el-form>


        <solt name="footer" style="padding-left: 70%">
          <el-button @click="handleBeforeClose">取 消</el-button>
          <el-button type="primary" @click="handleConfirm">确 定</el-button>
        </solt>
      </el-dialog>
    </div>
    <div>
      <el-dialog v-model="judgesDialog" title="分配评委" :visible="judgesDialog" width="80%"
        :before-close="handleBeforeClose">
        <el-form :model="judgesFromData" label-position="left" ref="judgesFormRef">
          <el-form-item label="选择评委" prop="judgesList">
            <el-select v-model="judgesFromData.selectedJudges" multiple>
              <el-option v-for="(option, index) in judgesOptions" :key="index" :label="option.nickName"
                :value="option.userId"></el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <solt name="footer" style="padding-left: 75%">
          <el-button @click="handleBeforeClose">取 消</el-button>
          <el-button type="primary" @click="handleJudgesConfirm">确 定</el-button>
        </solt>
      </el-dialog>
    </div>
  </div>
</template>

<style></style>